﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TireService.Data;
using System.Web.Security;

namespace TireService.Web.View.AdminView
{
    public partial class DeactivateSubscription : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Page.IsPostBack != true)
            {
                try
                {
                    if (Request.QueryString["Message"] != null)
                    {
                        lMessage.Text = Request.QueryString["Message"].ToString();
                        upMessage.Update();    
                    }
                }
                catch (Exception)
                {
                    // Nothing
                }

                try 
	            {	        
		            // Get customer subscription to deactivate
                    int CustomerSubscriptionId = Convert.ToInt32(Request.QueryString["CustomerSubscriptionId"]);

                    // Initiate data layer
                    TireServiceDB db = new TireServiceDB();

                    CustomerSubscription customersubscription = db.GetCustomerSubscription(CustomerSubscriptionId);

                    if (customersubscription == null)
                    {
                        throw new ArgumentException("Abonnement ikke fundet.");
                    }
                    else
                    {
                        // Show deactivation panel
                        pDeactivateSubscription.Visible = true;
                        pSubscriptionSelection.Visible = false;

                        // Get customer information
                        Customer customer = db.GetCustomer(customersubscription.CustomerId);
                        lblCustomerNameValue.Text = customer.Name;
                        lblCustomerAddressValue.Text = customer.Address;
                        lblCustomerZipCodeCityValue.Text = customer.ZipCode + " - " + customer.City;
                        lblCustomerEmailValue.Text = customer.Email;

                        // Get subscription information
                        Subscription subscription = db.GetSubscription(customersubscription.SubscriptionId);

                        lblSubscriptionString.Text = customer.CustomerId.ToString() + "-" + customersubscription.SubscriptionId.ToString() + "-" + customersubscription.CustomerSubscriptionId.ToString();
                        lblCustomerSubscriptionIdValue.Text = customersubscription.CustomerSubscriptionId.ToString();
                        lblSubscriptionValue.Text = subscription.Description;

                        // Get car information
                        List<Car> cars = db.GetCarByCustomerSubscriptionId(customersubscription.CustomerSubscriptionId);
                        if (cars.Count > 0)
                        {
                            int i = 0;
                            foreach (Car car in cars)
                            {
                                if (i == 0)
                                {
                                    lblCarValue.Text = db.GetCarBrandDescription(car.CarBrandId) + "(Reg: " + car.RegistrationNumber + ", Årgang: " + car.Year.ToString() + ", Farve: " + car.Color + ")";
                                }
                                else
                                {
                                    lblCarValue2.Text = db.GetCarBrandDescription(car.CarBrandId) + "(Reg: " + car.RegistrationNumber + ", Årgang: " + car.Year.ToString() + ", Farve: " + car.Color + ")";
                                }

                                i += 1;
                            }
                        }
                    }
	            }
	            catch (Exception)
	            {
		            // Error occured - customer subscription not found. Hide deactivation panel and show subscription selection panel
                    pDeactivateSubscription.Visible = false;
                    pSubscriptionSelection.Visible = true;
	            }
                
            }
        }

        /// <summary>
        /// Function that redirect to this page againg - thereby refreshing it
        /// </summary>
        private void ResetDeactivationForm(string Message)
        {
            if (Message != null)
            {
                Response.Redirect("~/View/AdminView/DeactivateSubscription.aspx?Message=" + Message.ToString());
            }
            else
            {
                Response.Redirect("~/View/AdminView/DeactivateSubscription.aspx");
            }
        }

        /// <summary>
        /// Button function that deactivates a customer subscription
        /// </summary>
        protected void btnDeactivateSubscription_Click(object sender, EventArgs e)
        {
            try
            {
                // Initiate data layer
                TireServiceDB db = new TireServiceDB();

                // Deactivate subscription
                CustomerSubscription customersubscription = db.GetCustomerSubscription(Convert.ToInt32(lblCustomerSubscriptionIdValue.Text));

                //if (customersubscription.InActive)
                //{
                //    throw new ArgumentException("Abonnement er allerede deaktiveret.");
                //}

                // Initiate business logic - create log
                CustomerSubscriptionLogBLL customersubscriptionBLL = new CustomerSubscriptionLogBLL();

                customersubscription.InActiveDate = DateTime.Now;
                customersubscription.InActive = true;

                // Get userid
                Guid UserId = new Guid(Membership.GetUser().ProviderUserKey.ToString());

                // Add note if any
                string note = "Abonnement opsagt, hjul udleveret";
                if (txtDeactivationNote.Text != "") note = note + " - Bemærkning: " + txtDeactivationNote.Text;

                // Create subscription log
                customersubscriptionBLL.CreateCustomerSubscriptionLog(db, customersubscription, (int)Shared.SubscriptionLogAction.DeActivated, UserId, note);

                // Deactive Cars related to customer subscription
                List<Car> cars = db.GetCarByCustomerSubscriptionId(customersubscription.CustomerSubscriptionId);

                foreach (Car car in cars)
                {
                    car.CarStatusId = (int)Shared.CarStatus.InActive;

                    // Check if tireset should be removed from stock
                    if (cbReleaseTireSetFromContainer.Checked)
                    {
                        List<TireSet> tiresets = db.GetTireSets(car.CarId);

                        TireSetLogBLL tiresetlogBLL = new TireSetLogBLL();

                        foreach (TireSet tireset in tiresets)
                        {
                            if (tireset.ContainerCargoRoomId != null)
                            {
                                // Create TireSet log
                                tiresetlogBLL.CreateTireSetLog(db, tireset, DateTime.Now, tireset.TireSetStatusId, (int)Shared.TireSetStatus.ReturnedToCustomer, UserId, note, null, null, null, null, null);

                                // Release tireset from container/stock
                                tireset.ContainerCargoRoomId = null;
                                tireset.TireSetStatusId = (int)Shared.TireSetStatus.ReturnedToCustomer;
                            }
                        }
                    }
                }

                // Check if open serviceschedules should be marked as completed
                if (cbCompleteOpenServiceSchedules.Checked)
                {
                    List<BusinessServiceListView> services = db.GetCustomerService(customersubscription.CustomerId, true).Where(p => p.WorkCompleted == false).ToList();

                    foreach (BusinessServiceListView service in services)
                    {
                        ServiceCarScheduleDetail detail = db.GetServiceCarScheduleDetail(service.ServiceCarScheduleDetailId);
                        detail.WorkCompleted = true;
                    }
                }

                // Check if receipt to customer should be generated
                if (cbReceiptTireSet.Checked)
                {
                    // TODO: Create this    
                }

                // Check if email should be send to customer
                if (cbDeactivateSubscriptionSendEmail.Checked)
                {
                    // TODO: Create this    
                }

                // Commit changes to database
                db.SubmitChanges();

                // Sync with economic
                // Check if sync is required
                if (db.GetCustomerSyncToEconomic(customersubscription.CustomerId))
                {
                    // Update customer subscription in E-conomic
                    EconomicInterface ecoInterface = new EconomicInterface();

                    ecoInterface.ExpireSubscriber(customersubscription.SubscriptionId, customersubscription);
                }

                // Dispose database connection
                db.Dispose();

                // Reset deactivate subscription form
                ResetDeactivationForm("Abonnement blev deaktiveret");
            }
            catch (Exception ex)
            {
                lMessage.Text = ex.Message.ToString();
            }
            finally
            {
                upMessage.Update();
            }
        }

        /// <summary>
        /// Button function that reset deactivation form
        /// </summary>
        protected void btnResetDeactivation_Click(object sender, EventArgs e)
        {
            ResetDeactivationForm(null);
        }
    }
}